import ErrorMessage from "@src/components/ErrorMessage";
import {
  AccountManageV1Client,
  AppUser,
  PagedListOfAppUser,
  Paging,
  QueryUsersCommand,
} from "@src/services/v1_client";
import { useClient } from "@src/utils/useHelper";
import {
  BootstrapIcon,
  BsButton,
  formatDate,
  Loading,
  Pagination,
  SolidModal,
  SubTotal,
  Table,
} from "solid-fire-controls";
import {
  catchError,
  Component,
  createEffect,
  createMemo,
  createResource,
  createSignal,
} from "solid-js";
import UserDetail from "./Detail";
import { fetchUserDetail } from "./functions";
import { Modal } from "bootstrap";
import { handleError } from "@src/utils/http-utils";

const manageClient = useClient(AccountManageV1Client);

const defaultSize = 20;
const defaultResult = new PagedListOfAppUser({ totalCount: 0 });

const UserList: Component = () => {
  const [paging, setPaging] = createSignal(
    new Paging({ index: 1, size: defaultSize })
  );

  const loadUsers = async (p: Paging) => {
    return await manageClient.queryUsers(new QueryUsersCommand({ paging: p }));
  };

  const loadUserDetail = (id?: string) => {
    if (!id) {
      return Promise.resolve(undefined);
    }

    return fetchUserDetail(id);
  };

  const [resource, { mutate, refetch }] = createResource(paging(), loadUsers);

  const delayedLoading = createMemo(() => {
    return resource.loading;
  });

  const [userList, setUserList] = createSignal<PagedListOfAppUser | undefined>(
    defaultResult
  );

  const errorHandler = (err: Error) => {};

  createEffect(() => {
    catchError(() => {
      setUserList(resource() ?? defaultResult);
    }, errorHandler);
  });

  const refresh = () => {
    catchError(() => {
      Promise.resolve(refetch());
    }, errorHandler);
  };

  const [loadingDetail, setLoadingDetail] = createSignal(false);
  const viewDetail = (userId: string) => {
    setViewingUserId(userId);
    detailModal()?.show();
    setLoadingDetail(true);
    loadUserDetail(userId)
      .then((user) => setViewingUser(user))
      .catch(handleError)
      .finally(() => setLoadingDetail(false));
  };

  // createEffect(on(resource, (v) => console.log("users", v)));
  // createEffect(() => console.log("loading", resource.loading));

  const [viewingUserId, setViewingUserId] = createSignal<string | undefined>(
    undefined
  );
  const [viewingUser, setViewingUser] = createSignal<AppUser | undefined>(
    undefined
  );

  const [detailModal, setDetailModal] = createSignal<Modal | undefined>(
    undefined
  );

  return (
    <div class="d-flex p-2 flex-column h-100" style={{ "max-height": "100%" }}>
      <ErrorMessage
        error={resource.error}
        show={resource.state === "errored"}
      ></ErrorMessage>
      <div class="flex-shrink-1">
        <BsButton
          variant={"primary"}
          loading={delayedLoading()}
          onClick={refresh}
        >
          刷新
        </BsButton>
        {/* <button type="button" class="btn btn-primary" onclick={refresh}>
            刷新
          </button> */}
      </div>
      <Table
        size="sm"
        loading={delayedLoading()}
        classList={{
          "flex-grow-1": true,
          "mt-2": true,
          "mb-2": true,
        }}
        responsive
        fixedHeader
        border={"borderless"}
        hover
        nowrap
        datas={userList()?.datas}
        columns={[
          {
            type: "selection",
          },
          {
            type: "index",
          },
          {
            name: "userName",
            label: "用户名",
            fixed: "left",
            width: 120,
            tooltip: true,
            headerAlign: "center",
          },
          {
            name: "email",
            label: "邮件地址",
          },
          {
            name: "createdTime",
            label: "创建时间",
            children: formatDate(),
          },
          {
            name: "lastModifiedTime",
            label: "最后修改时间",
            children: formatDate(),
          },
          {
            name: "phoneNumber",
            label: "电话号码",
          },
          {
            name: "accessFailedCount",
            label: "访问失败次数",
            footer: SubTotal,
          },
          {
            label: "操作",
            fixed: "right",
            width: 100,
            children: (data, index) => (
              <>
                <button
                  type="button"
                  class="btn btn-sm btn-primary"
                  onclick={() => viewDetail(data.id!)}
                >
                  <BootstrapIcon icon="search" class="me-1" />
                  查看
                </button>
              </>
            ),
          },
        ]}
        slots={{
          header: (ctx) => (
            <Table.Header
              {...ctx}
              classList={{ ...ctx.classList, "table-primary": true }}
            ></Table.Header>
          ),
        }}
      ></Table>
      <div>
        <Pagination
          showTotal
          classList={{ "justify-content-center": true }}
          totalCount={userList()?.totalCount}
          current={{ page: paging().index!, size: paging().size! }}
          onChanged={(page, size) =>
            setPaging(new Paging({ index: page, size }))
          }
        ></Pagination>
      </div>
      <SolidModal
        fullscreen
        onRef={setDetailModal}
        onHidden={() => {
          setViewingUserId(undefined);
          setViewingUser(new AppUser());
        }}
      >
        <Loading show={loadingDetail()}>
          <SolidModal.Header>
            <SolidModal.Title classList={{ "fs-4": true }}>
              {viewingUserId()}
            </SolidModal.Title>
            <SolidModal.CloseButton></SolidModal.CloseButton>
          </SolidModal.Header>
          <SolidModal.Body>
            <UserDetail user={viewingUser()} disabled></UserDetail>
          </SolidModal.Body>
        </Loading>
      </SolidModal>
    </div>
  );
};

export default UserList;
